﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using BrainTechLLC;
using ImageAppDataModels;
using ImageAppViewModels;

namespace FullViewer.Plugin
{
    /// <summary>
    /// Interaction logic for FullViewerWindow.xaml
    /// </summary>
    public partial class FullViewerWindow : Window
    {
        public event EventHandler<ObjectEventArgsNonRef<FileImageViewModel, bool>> RequestDelete;
        public event EventHandler<ObjectEventArgsNonRef<FileImageViewModel, bool>> RequestResizeDelete;
        public event EventHandler<ObjectEventArgsNonRef<FileImageViewModel, bool>> RequestResize;
        public event EventHandler<ObjectEventArgsNonRef<RotationParams, bool>> RequestRotate;

        public event EventHandler WantNextImage;
        public event EventHandler WantPreviousImage;        
        int _imagesViewed = 0;

        public static readonly DependencyProperty FileImageViewModelProperty =
            DependencyProperty.Register("FileImageViewModel", typeof(FileImageViewModel), typeof(FullViewerWindow), new PropertyMetadata(null, OnFileImageViewModelPropertyChanged));

        public FileImageViewModel FileImageViewModel
        {
            get { return (FileImageViewModel)GetValue(FileImageViewModelProperty); }
            set { SetValue(FileImageViewModelProperty, value); }
        }

        private static void OnFileImageViewModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FullViewerWindow source = d as FullViewerWindow;
            FileImageViewModel v = e.NewValue as FileImageViewModel;
            FileImageViewModel vOld = e.OldValue as FileImageViewModel;
            source.UpdateFileImageViewModel(v, vOld);
        }

        public void UpdateFileImageViewModel(FileImageViewModel viewModel, FileImageViewModel viewModelOld)
        {
            fullView.FullViewerWindow = this;
            FileImageViewModel = viewModel;
            fullView.FileImageViewModel = viewModel;
            primGrid.DataContext = FileImageViewModel;
        }

        public void FitOriginalSize()
        {
            FitImage(FileImageViewModel.LastOriginalBitmapWidth, FileImageViewModel.LastOriginalBitmapHeight);
        }

        public System.Drawing.Rectangle WorkingArea
        {
            get { return Screen.PrimaryScreen.WorkingArea; }
        }

        public void FitSaved()
        {
            double width = Settings.Values.FullWidth;
            double height = Settings.Values.FullHeight;
            bool first = false;

            if (width == 0D || height == 0D)
            {
                width = this.ActualWidth;
                height = this.ActualHeight;
                this.WindowState = WindowState.Maximized;
                first = true;
            }

            this.FitThis(width, height);
            this.Fit(width, height);

            if (!first && this.WindowState != Settings.Values.FullWindowState)
            {
                this.WindowState = Settings.Values.FullWindowState;
            }
        }

        public void FitThis(double width, double height)
        {
            this.Width = width;
            this.Height = height;
        }

        public void Fit()
        {
            Fit(this.ActualWidth, this.ActualHeight);
        }

        public double GetWidth(double width)
        {
            return width;            
        }

        public double GetHeight(double height)
        {
            return height - 6;
        }

        public void FitScroller(double width, double height)
        {
            fullView.scroller.Width = GetWidth(width);
            fullView.scroller.Height = GetHeight(height);
        }

        public void FitImage(double width, double height)
        {
            fullView.imgMain.Width = GetWidth(width);
            fullView.imgMain.Height = GetHeight(height);
        }

        public void FitView(double width, double height)
        {
            fullView.Width = GetWidth(width);
            fullView.Height = GetHeight(height);            
        }

        public void Fit(double width, double height)
        {
            if (width <= 10 || height <= 10)
                return;

            FitView(width, height);
            FitScroller(width, height);
            FitImage(width, height);
        }

        public void FitFullScreen()
        {
            System.Drawing.Rectangle area = WorkingArea;
            Fit(area.Width, area.Height);
        }

        public void FitToScreen()
        {
            Fit(this.ActualWidth, this.ActualHeight);
        }

        public FullViewerWindow()
        {
            InitializeComponent();
            Closing += new System.ComponentModel.CancelEventHandler(FullViewerWindow_Closing);
        }

        private void FullViewerWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Settings.Values.FullHeight = this.ActualHeight;
            Settings.Values.FullWidth = this.ActualWidth;
            Settings.Values.FullLeft = this.Left;
            Settings.Values.FullTop = this.Top;
            Settings.Values.FullWindowState = this.WindowState;
            DecoupleEvents();

            FileImageViewModel = null;

            var toClear = RecentlyUsedFileImages.RecentlyUsedImageSources.Clear();

            foreach (var item in toClear)
            {
                item._imageSource = null;
                item.RaisePropertyChanged("ImageSource");
            }
        }

        public void HookupEvents()
        {
            SizeChanged += new SizeChangedEventHandler(FullViewerWindow_SizeChanged);
            LocationChanged += new EventHandler(FullViewerWindow_LocationChanged);
        }

        public void DecoupleEvents()
        {
            SizeChanged -= FullViewerWindow_SizeChanged;
            LocationChanged -= FullViewerWindow_LocationChanged;
        }

        void FullViewerWindow_LocationChanged(object sender, EventArgs e)
        {
            Settings.Values.FullLeft = this.Left;
            Settings.Values.FullTop = this.Top;
        }

        void FullViewerWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            FitToScreen();
            Settings.Values.FullWidth = this.ActualWidth;
            Settings.Values.FullHeight = this.ActualHeight;
            Settings.Values.FullWindowState = this.WindowState;
        }
        
        public void OnWantNextImage()
        {            
            if (_imagesViewed++ > 10 || RecentlyUsedFileImages.RecentlyUsedImageSources.Count > 10)
            {
                _imagesViewed = 0;
                var toClear = RecentlyUsedFileImages.RecentlyUsedImageSources.Clear();

                foreach (var item in toClear)
                {
                    item._imageSource = null;
                    item.RaisePropertyChanged("ImageSource");
                }
            }

            if (WantNextImage != null)
                WantNextImage(this, EventArgs.Empty);
        }

        public void OnWantPreviousImage()
        {         
            if (_imagesViewed++ > 10 || RecentlyUsedFileImages.RecentlyUsedImageSources.Count > 10)
            {
                _imagesViewed = 0;
                var toClear = RecentlyUsedFileImages.RecentlyUsedImageSources.Clear();

                foreach (var item in toClear)
                {
                    item._imageSource = null;
                    item.RaisePropertyChanged("ImageSource");
                }
            }

            if (WantPreviousImage != null)
                WantPreviousImage(this, EventArgs.Empty);
        }

        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
            else if (e.Key == Key.OemPlus)
            {
                fullView.Zoom();
            }
            else if (e.Key == Key.Delete || e.Key == Key.D)
            {
                RequestDelete.RaiseEvent(this, this.FileImageViewModel, false);                
            }
            else if (e.Key == Key.OemMinus)
            {
                fullView.Shrink();
            }
            else if (e.Key == Key.F)
            {
                FitToScreen();
            }
            else if (e.Key == Key.O)
            {
                FitOriginalSize();
            }
            else if (e.Key == Key.NumPad3 || e.Key == Key.PageDown || e.Key == Key.Space)
            {
                OnWantNextImage();
            }
            else if (e.Key == Key.NumPad9 || e.Key == Key.PageUp)
            {
                OnWantPreviousImage();
            }
            else if (e.Key == Key.Down)
            {
                fullView.scroller.ScrollToVerticalOffset(fullView.scroller.VerticalOffset + 100);
            }
            else if (e.Key == Key.Up)
            {
                fullView.scroller.ScrollToVerticalOffset(fullView.scroller.VerticalOffset - 100);
            }
            else if (e.Key == Key.Right)
            {
                fullView.scroller.ScrollToHorizontalOffset(fullView.scroller.HorizontalOffset + 100);
            }
            else if (e.Key == Key.Left)
            {
                fullView.scroller.ScrollToHorizontalOffset(fullView.scroller.HorizontalOffset - 100);
            }
            else
            {
                // TODO
                //string s = e.Key.ToString();
                //if (s[0] == 'D')
                //{
                //    char c = s[1];

                //    if (c >= '0' && c <= '9')
                //    {
                //        DataLoader._metaData.AddMetaData(FileImageViewModel.FileName, (double)(c - '0'));
                //    }
                //}
            }
        }

        private void fullView_RequestDelete(object sender, ObjectEventArgsNonRef<FileImageViewModel, bool> e)
        {
            RequestDelete.RaiseEvent(this, e.obj1, e.obj2);            
        }

        private void fullView_RequestResize(object sender, ObjectEventArgsNonRef<FileImageViewModel, bool> e)
        {
            RequestResize.RaiseEvent(this, e.obj1, e.obj2);
        }

        private void fullView_RequestResizeDelete(object sender, ObjectEventArgsNonRef<FileImageViewModel, bool> e)
        {
            RequestResizeDelete.RaiseEvent(this, e.obj1, e.obj2);
        }

        private void fullView_RequestRotate(object sender, ObjectEventArgsNonRef<RotationParams, bool> e)
        {
            RequestRotate.RaiseEvent(this, e.obj1, e.obj2);
        }
    }
}
